#!/usr/bin/env python

import getopt
import threading
import sys
from time import time,ctime
from socket import *


max_thread = 10

def useage():
    print
    print "Useage:"
    print
    print "pyScan -s <start port> -e <end port> -h <target_ip>"
    print

class scan(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        self.host = host
        self.port = port
        try:
            self.sk = socket(AF_INET, SOCK_STREAM)
        except:
            print "socket error"
            sys.exit(1)
        self.sk.settimeout(0.1)

    def run(self):
        try:
            self.sk.connect((self.host, self.port))
        except:
            pass
        else:
            
            print "%s\t%d OPEN %s" % (ctime(time()), self.port, getservbyport(self.port))
            self.sk.close()

class pyScanner:
    def __init__(self, args = []):
        try:
            opts, argvs = getopt.getopt(args[1:],"s:e:h:")
        except getopt.GetoptError:
            useage()
            sys.exit(1)
            
        for opt, argv in opts:
            
            if opt == '-s':
                try:
                    self.start = int(argv)
                except ValueError:
                    print "Invaild option: -s"+argv
                    useage()
                    sys.exit(1)
                    
            elif opt == "-e":
                try:
                    self.end = int(argv)
                except ValueError:
                    print "Invaild option: -e"+argv
                    useage()
                    sys.exit(1)
                    
            elif opt == "-h":
                self.host = argv
                
        if self.start > self.end:
            print "Port range error"
            useage()
            sys.exit(1)

        try:
            gethostbyname(self.host)
        except:
            print "Hostname '%s' unknown" % self.host
            
        self.do_scan(self.host, self.start, self.end)

    def do_scan(self, host, start, end):
        self.port = start
        while self.port <= end:
            while threading.activeCount() < max_thread:
                scan(host, self.port).start()
                self.port += 1
            
if __name__ == "__main__":
    pyScanner(sys.argv)
